﻿using EShop.Net.IRepository.Advert;
using EShop.Net.IRepository.UnitOfWork;
using EShop.Net.IServices.Advert;
using EShop.Net.Loging;
using EShop.Net.Model.Entity;
using Microsoft.Extensions.FileProviders;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace EShop.Net.Services.Advert
{
    /// <summary>
    /// 广告表业务逻辑  接口实现
    /// </summary>
    public class AdvertService : BaseServices<Advertisement>, IAdvertService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IAdvertRepository _db;
        private readonly IAdvertRepository _IadvertRepository;

        public AdvertService(IUnitOfWork unitOfWork, IAdvertRepository db, IAdvertRepository iadvertRepository)
        {
            this._unitOfWork = unitOfWork;
            this._db = db;
            BaseDal = db;
            this._IadvertRepository = iadvertRepository;
        }

        /// <summary>
        /// 首页获取广告图
        /// </summary>
        /// <param name="host">项目域名</param>
        /// <param name="rootPath">Api项目根路径</param>
        /// <returns></returns>
        public async Task<List<Advertisement>> SelectAdvert(string host, IFileProvider rootPath)
        {
            try
            {
                List<Advertisement> advertisements = new List<Advertisement>();
                var advertInfo = await this._IadvertRepository.QueryAsync();
                foreach (var item in advertInfo)
                {
                    // 在给定的路径查找某个文件
                    IFileInfo file = rootPath.GetFileInfo("/wwwroot/static/images/banner/" + item.advertPath);
                    // 如果基础存储系统中存在资源，则为 True。
                    if (file.Exists)
                    {
                        Advertisement advertisement = new Advertisement()
                        {
                            advertisingName = item.advertisingName,
                            advertPath = "https://" + host + "/static/images/banner/" + item.advertPath,
                            positionId = item.positionId,
                        };
                        advertisements.Add(advertisement);
                    }
                }
                return advertisements;
            }
            catch (Exception e)
            {
                NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.BusinessLogic, "首页获取广告图", "SelectAdvert业务逻辑错误", e);
                return null;
            }
        }
    }
}
